package com.example.currentlimiting.demo;

import com.google.common.util.concurrent.RateLimiter;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@SpringBootTest
public class CurrentLimitingDemo1 {

    private static RateLimiter rateLimiter;

    @Test
    public void pools() {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        RateLimiter rateLimiter = RateLimiter.create(1);
        List<Runnable> tasks = new ArrayList<Runnable>();
        for (int i = 0; i < 10; i++) {
            tasks.add(new UserRequest(i));
        }
        for (Runnable runnable : tasks) {
            System.out.println(">>>等待时间：" + rateLimiter.acquire());
            executor.execute(runnable);
        }
    }

    class UserRequest implements Runnable {
        private int id;

        public UserRequest(int id) {
            this.id = id;
        }

        public void run() {
            System.out.println(">>>id: " + id);
        }
    }

}
